/*
 * Copyright (c) 2024.  little3201.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *       https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.server.starter.exploiter.service.impl;

import com.server.starter.exploiter.domain.Field;
import com.server.starter.exploiter.dto.FieldDTO;
import com.server.starter.exploiter.repository.FieldRepository;
import com.server.starter.exploiter.service.FieldService;
import com.server.starter.exploiter.vo.FieldVO;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
public class FieldServiceImpl implements FieldService {

    private final FieldRepository fieldRepository;

    public FieldServiceImpl(FieldRepository fieldRepository) {
        this.fieldRepository = fieldRepository;
    }

    @Override
    public List<FieldVO> findAllBySchemaId(Long schemaId) {
        return fieldRepository.findAllBySchemaId(schemaId).stream().map(this::convert).toList();
    }

    @Override
    public List<FieldVO> modifyAll(Long schemaId, List<FieldDTO> dtoList) {
        Map<String, Field> fieldMap = fieldRepository.findAllBySchemaId(schemaId).stream()
                .collect(Collectors.toMap(Field::getColumnName, field -> field));

        List<Field> fields = new ArrayList<>(dtoList.size());
        dtoList.stream().filter(fieldDTO -> Objects.equals(schemaId, fieldDTO.getSchemaId()))
                .forEach(dto -> {
                    if (fieldMap.containsKey(dto.getColumnName())) {
                        Field existingField = fieldMap.get(dto.getColumnName());
                        convert(dto, existingField);
                        fields.add(existingField);
                    }
                });
        Iterable<Field> savedFields = fieldRepository.saveAll(fields);
        return StreamSupport.stream(savedFields.spliterator(), false)
                .map(field -> convert(field, FieldVO.class)).toList();
    }

    /**
     * 类型转换
     *
     * @param field 信息
     * @return FieldVO 输出对象
     */
    private FieldVO convert(Field field) {
        return convert(field, FieldVO.class);
    }
}
